package com.gt.framework.web.service;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.gt.common.constant.CacheConstants;
import com.gt.common.constant.Constants;
import com.gt.common.core.domain.entity.SysUser;
import com.gt.common.core.domain.model.LoginUser;
import com.gt.common.core.redis.RedisCache;
import com.gt.common.enums.UserType;
import com.gt.common.exception.ServiceException;
import com.gt.common.exception.user.CaptchaException;
import com.gt.common.exception.user.CaptchaExpireException;
import com.gt.common.exception.user.UserPasswordNotMatchException;
import com.gt.common.utils.DateUtils;
import com.gt.common.utils.MessageUtils;
import com.gt.common.utils.ServletUtils;
import com.gt.common.utils.StringUtils;
import com.gt.common.utils.ip.IpUtils;
import com.gt.framework.manager.AsyncManager;
import com.gt.framework.manager.factory.AsyncFactory;
import com.gt.framework.security.context.AuthenticationContextHolder;
import com.gt.framework.security.wxauth.SsoAuthenticationToken;
import com.gt.framework.security.wxauth.WeChatAuthenticationToken;
import com.gt.sso.domain.SysSso;
import com.gt.sso.service.ISysSsoService;
import com.gt.sso.vo.SsoLoginUser;
import com.gt.system.mapper.SysUserMapper;
import com.gt.system.service.ISysConfigService;
import com.gt.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 登录校验方法
 *
 * @author fish
 */
@Component
public class SysLoginService {
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private ISysSsoService ssoService;

    @Value("${wx.WXDefaultAvatar}")
    private String WXDefaultAvatar;

    @Autowired
    private SysUserMapper userMapper;

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid) {
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        // 验证码开关
        if (captchaEnabled) {
            validateCaptcha(username, code, uuid);
        }
        // 用户验证
        Authentication authentication = null;
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        } finally {
            AuthenticationContextHolder.clearContext();
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid) {
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
            throw new CaptchaException();
        }
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId) {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @return 结果
     */
    public String login(String username, String password) {
        boolean captchaEnabled = configService.selectCaptchaEnabled();

        // 用户验证
        Authentication authentication = null;
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        } finally {
            AuthenticationContextHolder.clearContext();
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 通过openid登录
     *
     * @param openid
     * @return
     */
    public LoginUser openIdLogin(String openid) {
        // 用户验证
        Authentication authentication = null;
        SysUser sysUser = null;
        LoginUser loginUser = null;
        Boolean flag = true;
        try {
            sysUser = userService.selectUserByOpenId(openid);
            if (sysUser == null) {
                sysUser = new SysUser();
                sysUser.setNickName("微信用户" + openid.substring(0, 9));
                sysUser.setUserName(openid);
                sysUser.setOpenId(openid);
                sysUser.setAvatar(WXDefaultAvatar);
                sysUser.setCreateTime(new Date());
                sysUser.setUserType(UserType.WX.getType());
                flag = false;
                userService.insertUser(sysUser);
            }
            WeChatAuthenticationToken weChatAuthenticationToken = new WeChatAuthenticationToken(openid, null);
            AuthenticationContextHolder.setContext(weChatAuthenticationToken);
            authentication = authenticationManager
                    .authenticate(weChatAuthenticationToken);
        } catch (Exception e) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(openid, Constants.LOGIN_FAIL, e.getMessage()));
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(openid, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        loginUser = (LoginUser) authentication.getPrincipal();
        SysUser sysUser1 = userMapper.selectUserByUserId(openid);
        loginUser.setUser(sysUser1);
        loginUser.setUserId(sysUser1.getUserId());
        // 生成token
        String token = tokenService.createToken(loginUser);
        loginUser.setToken(token);
        if (flag) {
            loginUser.setIsNew("1");
        } else {
            loginUser.setIsNew("0");
        }
        return loginUser;
    }

    public String ssoLogin(SsoLoginUser ssoLoginUser) {
        //验证系统id
        SysSso sysSso = ssoService.getOne(Wrappers.<SysSso>lambdaQuery().eq(SysSso::getSysId, ssoLoginUser.getSystemId()));

        if (ObjectUtils.isEmpty(sysSso)) {
            return null;
        }

        String ssoName = ssoLoginUser.getSsoName();
        SysUser user = userService.getOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getSsoUsername, ssoName));
        if (user == null) {
            return null;
        }

        Authentication authentication = null;
        try {
            authentication = authenticationManager
                    .authenticate(new SsoAuthenticationToken(user.getUserName(), null));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(user.getUserName(), Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(user.getUserName(), Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(user.getUserName(), Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        // 生成token
        return tokenService.createToken(loginUser);
    }
}
